package com.xuecheng.filesystem.service;

import com.alibaba.fastjson.JSON;

import com.xuecheng.framework.domain.filesystem.FileSystem;
import com.xuecheng.framework.domain.filesystem.response.FileSystemCode;
import com.xuecheng.framework.domain.filesystem.response.UploadFileResult;
import com.xuecheng.framework.exception.ExceptionCast;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.filesystem.FilesystemRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 *
 */
@Service
@Slf4j
public class FileSystemService {
    @Value("${xuecheng.fastdfs.trackerServer}")
    private String trackerServer;

    @Value("${xuecheng.fastdfs.connect_timeout_in_seconds}")
    private Integer connect_timeout_in_seconds;

    @Value("${xuecheng.fastdfs.network_timeout_in_seconds}")
    private Integer network_timeout_in_seconds;

    @Value("${xuecheng.fastdfs.charset}")
    private String charset;

    @Autowired
    private FilesystemRepository filesystemRepository;

    public UploadFileResult uploadFile(MultipartFile file, String filetag, String businesskey, String metadata) {
       //
        if(file==null){
            ExceptionCast.cast(FileSystemCode.FS_UPLOADFILE_FILEISNULL);
        }

        //1、把文件上传到fastdfs
        String fileId = this.upload(file);

        //2、把文件信息保存到MongoDB
        FileSystem fileSystem = new FileSystem();
        fileSystem.setBusinesskey(businesskey);
        //fileSystem.setFileHeight(file.get);
        fileSystem.setFileId(fileId);
        fileSystem.setFileName(file.getOriginalFilename());
        fileSystem.setFilePath(fileId);
        fileSystem.setFiletag(filetag);
        fileSystem.setFileSize(file.getSize());
        fileSystem.setFileType(file.getContentType());
        if(StringUtils.isNotEmpty(metadata)){
            Map map = JSON.parseObject(metadata, Map.class);
            fileSystem.setMetadata(map);
        }

        filesystemRepository.save(fileSystem);
        return new UploadFileResult(CommonCode.SUCCESS,fileSystem);
    }


    //0、初始化配置信息
    private void initConfig(){
        try {
            ClientGlobal.initByTrackers(trackerServer);
            ClientGlobal.setG_charset(charset);
            ClientGlobal.setG_network_timeout(network_timeout_in_seconds);
            ClientGlobal.setG_connect_timeout(connect_timeout_in_seconds);
        } catch (Exception e) {
            log.error("初始化fastdfs异常：{}",e.getMessage());
            e.printStackTrace();
            ExceptionCast.cast(FileSystemCode.FS_UPLOADFILE_FILEISNULL);
        }
    }

    //1、把文件上传到fastdfs
    private String upload(MultipartFile file){
        this.initConfig();
        //
        TrackerClient trackerClient = new TrackerClient();

        try {
            TrackerServer trackerServer = trackerClient.getConnection();
            StorageServer storageServer = trackerClient.getStoreStorage(trackerServer);
            StorageClient1 storageClient1 = new StorageClient1(trackerServer, storageServer);
            byte[] fileBytes = file.getBytes();
            String originalFilename = file.getOriginalFilename();
            String ext = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            String fileId = storageClient1.upload_file1(fileBytes, ext, null);
            return fileId;
        } catch (Exception e) {
            log.error("初始化fastdfs异常：{}",e.getMessage());
            e.printStackTrace();
            ExceptionCast.cast(FileSystemCode.FS_UPLOADFILE_FILEISNULL);
            return null;
        }
    }
}
